package com.liao.myblog.controller.comment;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.liao.myblog.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class MyCommentController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ResponseBody
    @PostMapping(value = "/comment/kaptcha")
    public ResultVO<Object> kaptcha(@RequestBody Map<String, Object> d) throws IOException {
        String text = defaultKaptcha.createText();

        redisTemplate.opsForValue().set("commentVerifyCode", text);
        redisTemplate.expire("commentVerifyCode", 3, TimeUnit.MINUTES);

        ByteArrayOutputStream baos;
        BufferedImage image = defaultKaptcha.createImage(text);

        baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);


        Base64.Encoder encoder = Base64.getEncoder();       //jdk8以上Base64Encoder被弃用

        HashMap<String, Object> map = new HashMap<>();
        map.put("img", encoder.encodeToString(baos.toByteArray()));
//        return ResultUtil.getResult(map,ResultUtil.RESULT_SUCCESS);
        return new ResultVO<>(map);
    }

}
